import { GetModelService } from '../../service/model-service';
import { UIService } from '../../service/ui-service/ui.service';

/**
 * UI服务注册中心
 *
 * @export
 * @class UIServiceRegister
 */
export class UIServiceRegister {
  /**
   * 所有UIService Map对象
   *
   * @private
   * @static
   * @memberof UIServiceRegister
   */
  private static cacheMap: Map<string, UIService> = new Map();

  /**
   * 获取指定UIService
   *
   * @author chitanda
   * @date 2022-05-17 18:05:55
   * @static
   * @param {IContext} context
   * @param {string} entityKey
   * @return {*}
   */
  static async getService(context: IContext, entityKey: string = ''): Promise<any> {
    const service = UIServiceRegister.cacheMap.get(context.srfapplicationtag ? `${context.srfapplicationtag}_${entityKey}` : entityKey);
    if (!service) {
      const modelService = await GetModelService(context);
      const app = modelService.app;
      const entities = app.getAllPSAppDataEntities() || [];
      const entityModel = entities.find(e => {
        if (e.isFill) {
          return e.codeName.toLowerCase() === entityKey.toLowerCase();
        }
        return e.refM.codeName?.toLowerCase() === entityKey.toLowerCase();
      });
      if (entityModel) {
        await entityModel.fill();
        const uiService = new UIService(entityModel, context);
        this.cacheMap.set(context.srfapplicationtag ? `${context.srfapplicationtag}_${entityKey}` : entityKey, uiService);
        return uiService;
      }
    }
    return service;
  }
}
